from plyny.presentation.table import Table

from mako.template import Template

import sys

class HtmlTable(Table):
    def render(self):
        return make_simple_table(self.rows, False, self.justifications, None)


def make_simple_table(rows, distinct_final_row=False, justifications=None, cols=None):
    # assume that all rows have same number of columns
    if not cols:
        cols = len(rows[0])
    return Template(u"""<thead>
<tr>
% for v in rows[0][:-1]:
<th>${v}</th> \\
% endfor
<th>${rows[0][-1]}</th>
</tr>
</thead>

<tbody>
% for row in rows[1:]:
<tr>
    % for v in row[:-1]:
<td>${v}</td> \\
    % endfor
<td>${row[-1]}</td>
</tr>
% endfor
</tbody>
""").render_unicode(rows=rows, distinct_final_row=distinct_final_row)


class _Trigger(object):
    def __del__(self):
        HTMLPrinter.switch()


class HTMLPrinter(object):
    @staticmethod
    def enable():
        HTMLPrinter.switch()
        return _Trigger()

    @staticmethod
    def switch():
        if isinstance(sys.stdout, HTMLPrinter):
            sys.stdout = sys.stdout.orig
        else:
            sys.stdout = HTMLPrinter()

    def __init__(self):
        self.orig = sys.stdout
        self.reset()
        self.orig.write('<html>\n<body>\n')

    def reset(self):
        self.buffer = [[]]
        self.tabbing = False
        self.tabbing_complete = False

    def _line_completed(self):
        if self.tabbing and '\t' not in ''.join(self.buffer[-1]):
            self.tabbing_complete = True

        def tab_to_td(line):
            return ''.join('<td>%s' % tok for tok in line.split('\t'))

        keep = None

        if not self.tabbing or self.tabbing_complete:
            if self.tabbing_complete:
                keep = self.buffer[-1]
                self.buffer = self.buffer[:-1]
                to_print = ['<tr>' + tab_to_td(''.join(x)) for x in self.buffer]
                to_print = '<table>\n' + ''.join(to_print) + '</table>\n'
            else:
                to_print = '\n'.join(''.join(x) for x in self.buffer)
                to_print = to_print.replace('\n', '<br>\n')

            self.orig.write(to_print)
            self.reset()
            if keep is not None:
                self.write(''.join(keep))
            return True

        return False

    image_extensions = ('jpg', 'jpeg', 'gif', 'png')
    
    def _convert_token(self, s):
        ext = s.split('.')[-1].lower()

        if ext in self.image_extensions:
            s = '<img src="%s">' % s

        elif s.lower().startswith('http:'):
            s = '<a href="%s">%s</a>' % (s, s)

        return s

    def write(self, s):
        s = self._convert_token(s)
        self.buffer[-1].append(s)

        if '\t' in s:
            self.tabbing = True

        if '\n' in s:
            if not self._line_completed():
                self.buffer.append([])
    
    def debug(self, s):
        self.orig.write('DEBUG:' + s)
    
    def __del__(self):
        if len(self.buffer[0]) > 0:
            self.tabbing_complete = True
            self._line_completed()

        self.orig.write('</body>\n</html>\n')


if __name__ == '__main__':
    import sys

    print 'hi', 'sup', 'http://www.cs.unc.edu', 'http://www.cs.unc.edu/~karl/me.jpg'
    print 'hi', 'sup', 'http://www.cs.unc.edu'

    print 'hello    hi'
    print 'what up'
    print 'sdf'
    print 'yes  no'

    try:
        t = HTMLPrinter.enable()
        print 'yes'
        print 'no'
    except:
        pass
    print 'what up'
